package gdou.gym.sys.safe;

import gdou.gym.exception.ForbiddenException;
import gdou.gym.exception.SysException;
import gdou.gym.token.AllowAccessFor;
import gdou.gym.token.Authorization;
import gdou.gym.token.TokenIgnore;
import gdou.gym.token.TokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws SysException {
        String token = request.getHeader(Authorization.FromInputAuthorizationName);// 从 http 请求头中取出 token
        if (!(handler instanceof HandlerMethod)) return true;
        if ("OPTIONS".equals(request.getMethod())) return true;
        HandlerMethod method = (HandlerMethod) handler;
        if (method.hasMethodAnnotation(TokenIgnore.class)) return true;
        AllowAccessFor access = method.getMethodAnnotation(AllowAccessFor.class);
        if (check(token, access)) {
            return true;
        }
        throw new ForbiddenException();
    }

    public static boolean check(String token, AllowAccessFor access) {
        Authorization[] values;
        if (access == null || (values = access.value()).length == 0) return true;
        Authorization authorization = TokenUtil.getAuthorization(token);
        for (Authorization value : values) {
            if (value.equals(authorization)) return true;
        }
        return false;
    }


}
